#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
|===== Conference Bot Plugin ============
|= Admin Commands
|===== By: ==============================
|= Patrick Kennedy
|===== Current Version: =================
|= 1.0
|===== Description: =========================================
|= Admin only commands.
|===== Additional Comments: =================================
|= 
|============================================================"""

import os
import traceback

from utils import *

def init(bot):
	bot.addAdminCommand("reload",cmd_reload)
	bot.addAdminCommand("loadplugin",cmd_loadplugin)
	bot.addAdminCommand("unload", cmd_unload)
	bot.addAdminCommand("announce",cmd_announce)
	bot.addAdminCommand("kami",cmd_announce)
	bot.addHook("receive", hook_announce)
	bot.addAdminCommand("addmod", cmd_addmod)
	bot.addAdminCommand("delmod", cmd_delmod)
	
def unload(bot):
	bot.removeCommand(["reload", "loadplugin", "unload", "announce", "kami", "addmod", "delmod"])
	bot.removeHook('hook_announce')
	
def cmd_reload(bot,user,args):
	"""Reload parts of the bot.
Useage: Reload [conf | plugins | all]
* bot - Reloads all the bot's .ini files.
* plugins - reloads all the bots plugins.
* all/blank - reloads both options."""
	
	if args in ["conf","bot","ini","all", ""]:
		readall()
		readcore(bot)
		bot.msg(user,"Bot config reloaded.")
		debug('reloads',"All bot .ini files have been reloaded.")
		
	if args in ["plugin", "plugins", "all", ""]:
		loaded = []
		pluglog = file(os.path.join("errors","PluginError.log"), "a+")
		for i in bot.config.system.plugins.split(" "):
			try:
				a = open(os.path.join("plugins","plugin_%s.py") % i,"r").read()
				#This checks if the plugin is different
				#It also failsafes if the plugin was crashed at startup.
				if bot.pluginhash.get(i, 0) == hash(a):
					continue
				
				plugin = {}
				exec a in plugin
				if "unload" in plugin:
					plugin["unload"](bot)
				plugin["init"](bot)
				bot.pluginhash[i] = hash(a)
				loaded.append(i)
			except IOError:
				bot.error(user,'The plugin "plugin_%s.py" could not be found.' % args)
				continue
			except:
				traceback.print_exc()
				print >>pluglog, "\n Plugin error log for: ", i
				traceback.print_exc(None, pluglog)
				pluglog.close()
				bot.error(user, 'There was an error importing the plugin. A report has been logged.')
				continue
		
		if loaded == []:
			loaded.append("None to be refreshed.")
		bot.msg(user,"Plugins reloaded: " + " ".join(loaded))
		debug('reloads',"All bot plugins have been reloaded.")
		bot.refreshRoster()
	
def cmd_loadplugin(bot,user,plugin):
	"""Load a new plugin.
Usage: loadplugin <new plugin>
This will load a new plugin, which will be instantly ready for use."""
			
	if plugin in bot.config.system.plugins.split(" "):
		bot.error(user,"This plugin has already been loaded. To update it please use ')reload plugins'")
		
	else:
		try:
			a = open(os.path.join("plugins","plugin_%s.py") % plugin,"r").read()
			loaded_plugin = {}
			exec a in loaded_plugin
			loaded_plugin["init"](bot)
			bot.msg(user, "Loaded plugin: " + plugin)
			bot.config.system.plugins += " " + plugin
			bot.config.save()
			bot.pluginhash[plugin] = hash(a)
		except IOError:
			bot.error(user,'The plugin "plugin_%s.py" could not be found.' % plugin)
		except:
			traceback.print_exc(None, bot.pluglog)
			print >>bot.pluglog, "\n"
			bot.pluglog.close()
			traceback.print_exc()
			bot.error(user, 'There was an error importing the plugin. A report has been logged.')
			
def cmd_unload(bot, user, plugin):
	"""Unload a plugin.
Usage: )unload <plugin>
Note: This will not remove it from the start-up list."""
	if plugin not in bot.config.system.plugins.split(" "):
		bot.error(user, "This plugin hasn't been loaded or was spelled wrong.")
		return
		
	a = open(os.path.join("plugins","plugin_%s.py") % plugin,"r").read()
	loaded_plugin = {}
	exec a in loaded_plugin
	if "unload" not in loaded_plugin:
		bot.error(user, "This plugin has no unload procedures and cannot be unloaded.")
		return
	loaded_plugin["unload"](bot)
	bot.sys(user, "Unloaded plugin: %s" % plugin)

			
def cmd_view(bot, user, args):
	"""View a user's variables.
	Usage: /view <displayname>"""
	jid = getjid(args.split(' ',1)[0])
			
def cmd_announce(bot, user, msg):
	"""Send global messages.
	Usage: )announce <message>"""
	
	if not msg:
		bot.msg(user, cmd_me.__doc__)
		return
	
	bot.sendtoall(msg, butnot = [user], name = "Announcement", log = True)
	
def hook_announce(bot, args):
	user, name = getjid(args[0]), args[1]
	if not name == "Announcement":
		return False
	if [(unicode(jid),message) for (jid,(status,message)) in bot.getJidStatus(name).items() if status in ["dnd"]]:
		return True
	return False

			
def cmd_addmod(bot, user, args):
	"""Add a new moderator.
	Usage: /addmod <displayname>"""
	
	jid = getjid(args.split(' ',1)[0])
	
	if isuser(bot, jid):
		if bot.getJidStatus(jid).items() != []:
			addmod(jid)
			bot.msg(user, "%s is now a moderator." % getdisplayname(jid))
			bot.msg(jid, "%s has made you a moderator." % getdisplayname(user))
		else:
			bot.msg(user, "That user is offline, please wait for them to come online before adding them.")
	else:
		bot.msg(user, "That user doesn't exist. Please check the name.")
		
def cmd_delmod(bot, user, args):
	"""Remove a moderator.
	Usage: /delmod <displayname>"""
	
	jid = getjid(args.split(' ',1)[0])
	if isuser(bot, jid):
		if bot.getJidStatus(jid).items() != []:
			delmod(jid)
			bot.msg(user, "%s is no longer a moderator." % getdisplayname(jid))
			bot.msg(jid, "%s has removed your mod-ship." % getdisplayname(user))
		else:
			bot.msg(user, "That user is offline, please wait for them to come online before removing them.")
	else:
		bot.msg(user, "That user doesn't exist. Please check the name.")
